package com.gf.framework.weblog.aspect;

import com.gf.framework.weblog.annotation.WebLog;
import com.gf.framework.weblog.model.WebLogInfo;
import com.gf.framework.weblog.service.WebLogServiceImpl;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Objects;

/**
 * @author gaofei
 * @date 2022/6/13 21:32
 */
@Aspect
@Component
public class WebLogAspect {
    @Value("${spring.application.name:未知}")
    private String appName;

    @Autowired
    private WebLogServiceImpl webLogService;

    @Around("@annotation(com.gf.framework.weblog.annotation.WebLog)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = getHttpServletRequest();
        String url = request.getRequestURI();
        Object[] args = joinPoint.getArgs();

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        WebLog annotation = method.getAnnotation(WebLog.class);

        WebLogInfo webLogInfo = new WebLogInfo();
        webLogInfo.setAppName(appName);
        webLogInfo.setUrl(url);
        webLogInfo.setArgs(args);
        webLogInfo.setCallTime(LocalDateTime.now());
        long nowTime = System.currentTimeMillis();

        try {
            Object ret = joinPoint.proceed();
            webLogInfo.setSuccess(true);
            if (annotation.saveRet()) {
                webLogInfo.setRet(ret);
            }
            return ret;
        } catch (Throwable e) {
            webLogInfo.setSuccess(false);
            webLogInfo.setErrorMessage(e.getMessage());
            StackTraceElement[] elements = e.getStackTrace();
            if (elements != null && elements.length > 0) {
                webLogInfo.setStackList(new ArrayList<>(10));
                for (int i = 0; i < 10 && i < elements.length; i++) {
                    webLogInfo.getStackList().add(elements[i].toString());
                }
            }
            throw e;
        } finally {
            webLogInfo.setTimeConsuming((int) (System.currentTimeMillis() - nowTime));
            webLogService.send(webLogInfo);
        }
    }

    private HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }
}
